package com.hll.api.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.CRC32;

/**
 * @author xavier
 *测试新浪微博图床
 */
public class test {
    private static Pattern p = Pattern.compile("^[a-zA-Z0-9]{32}$");
    private static  Pattern p1 = Pattern.compile("^(https?://[a-z]{2}d.sinaimg.cn/)(large|bmiddle|mw1024|mw690|small|square|thumb180|thumbnail)(/[a-z0-9]{32}.(jpg|gif))$");
    public static void main(String[] args) {
        String username = "17809276647";
        String base64name = Base64.encode(username.getBytes());
        String password = "741720390he";
        String loginUrl = "https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)&_=1403138799543";
        String params = "entry=sso&gateway=1&from=null&savestate=30&useticket=0&pagerefer=&vsnf=1&su=" + base64name;
        params += "&service=sso&sp=" + password + "&sr=1920*1080&encoding=UTF-8&cdult=3&domain=sina.com.cn&prelt=0&returntype=TEXT";
        String cookies = getSinaCookies(loginUrl, params);
        //可以将此cookie保存下来,以后不需要登录,直接用此cookie
        if (cookies != null) {
            String[] cookiearr = cookies.split(";");
            for (String s : cookiearr) {
                if (s.startsWith("SUB") && !s.startsWith("SUBP")) {
                    cookies = s + ";";
                }
            }
        }
        System.out.println(upload("C:/Users/74172/Pictures/星空背景 绘画 夜空 4k壁纸_彼岸图网.jpg", cookies));
    }

    public static String upload(String filepath, String cookies) {
        String url = "http://picupload.service.weibo.com/interface/pic_upload.php?mime=image%2Fjpeg&data=base64&url=0&markpos=1&logo=&nick=0&marks=1&app=miniblog";
        Date date = new Date();
        long time = date.getTime();
        String dateline = time + "";
        dateline = dateline.substring(0, 10);
        url += "&cb=http://weibo.com/aj/static/upimgback.html?_wv=5&callback=STK_ijax_" + dateline;

        String s = uploadFile(url, new String[]{filepath}, cookies);
        System.out.println(s);
        s = s.substring(s.indexOf("code") - 2);
        JSONObject jo = JSON.parseObject(s);
        JSONObject data = jo.getJSONObject("data");
        int count = data.getIntValue("count");
        if (count > 0) {
            JSONObject pic1 = data.getJSONObject("pics").getJSONObject("pic_1");
            if (pic1.getIntValue("ret") == 1) {
                String pid = pic1.getString("pid");
                return getImageUrl(pid, 0, true);
            } else {
                return null;
            }

        } else {
            return null;
        }

    }

    public static String getImageUrl(String pid, int sizeidx, boolean https) {
        String[] sizeArr = new String[]{"large", "mw1024", "mw690", "bmiddle", "small", "thumb180", "thumbnail", "square"};
        pid = pid.trim();
        String size = sizeArr[sizeidx];
        // 传递 pid
        Matcher m = p.matcher(pid);

        if (m.matches()) {
            CRC32 crc32 = new CRC32();
            crc32.update(pid.getBytes());
            return (https ? "https" : "http") + "://" + (https ? "ws" : "ww")
                    + ((crc32.getValue() & 3) + 1) + ".sinaimg.cn/" + size
                    + "/" + pid + "." + (pid.charAt(21) == 'g' ? "gif" : "jpg");
        }
//        // 传递 url
        String url = pid;

        Matcher m1 = p1.matcher(url);
        if (m1.find()) {
            return m.group(1) + size + m.group(3);
        }
        return null;
    }

    public static String getSinaCookies(String loginurl, String params) {
        //登录
        try {
            URL url = new URL(loginurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            OutputStream out = conn.getOutputStream();
            out.write(params.getBytes());
            out.flush();
            out.close();
            StringBuilder sessionId = new StringBuilder();
            String cookieVal;
            String key;
            //取cookie
            for (int i = 1; (key = conn.getHeaderFieldKey(i)) != null; i++) {
                if ("set-cookie".equalsIgnoreCase(key)) {
                    cookieVal = conn.getHeaderField(i);
                    cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));
                    sessionId.append(cookieVal).append(";");
                }
            }
            return sessionId.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 多文件上传的方法
     *
     * @param actionUrl：上传的路径
     * @param uploadFilePaths：需要上传的文件路径，数组
     */
    public static String uploadFile(String actionUrl, String[] uploadFilePaths, String cookies) {
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        DataOutputStream ds = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine;

        try {
            // 统一资源
            URL url = new URL(actionUrl);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection connection = (HttpURLConnection) urlConnection;

            // 设置是否从httpUrlConnection读入，默认情况下是true;
            connection.setDoInput(true);
            // 设置是否向httpUrlConnection输出
            connection.setDoOutput(true);
            // Post 请求不能使用缓存
            connection.setUseCaches(false);
            // 设定请求的方法，默认是GET
            connection.setRequestMethod("POST");
            // 设置字符编码连接参数
            connection.setRequestProperty("Connection", "Keep-Alive");
            // 设置字符编码
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Cookie", cookies);
            // 设置请求内容类型
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            // 设置DataOutputStream
            ds = new DataOutputStream(connection.getOutputStream());
            for (String uploadFile : uploadFilePaths) {
                String filename = uploadFile.substring(uploadFile.lastIndexOf("//") + 1);
                ds.writeBytes(twoHyphens + boundary + end);
                ds.writeBytes("Content-Disposition: form-data; " + "name=\"pic1\";filename=\"" + filename + "\"" + end);
                ds.writeBytes(end);
                FileInputStream fStream = new FileInputStream(uploadFile);
                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int length;
                while ((length = fStream.read(buffer)) != -1) {
                    ds.write(buffer, 0, length);
                }
                ds.writeBytes(end);
                /* close streams */
                fStream.close();
            }
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            /* close streams */
            ds.flush();
            if (connection.getResponseCode() >= 300) {
                throw new Exception(
                        "HTTP Request is not success, Response code is " + connection.getResponseCode());
            }

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = connection.getInputStream();
                inputStreamReader = new InputStreamReader(inputStream);
                reader = new BufferedReader(inputStreamReader);
                resultBuffer = new StringBuffer();
                while ((tempLine = reader.readLine()) != null) {
                    resultBuffer.append(tempLine);
                    resultBuffer.append("\n");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ds != null) {
                try {
                    ds.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultBuffer.toString();
    }
}
